/**
 * 路由配置
 */
import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '@/store';
import setting from '@/config/setting';
import EleLayout from '@/layout';
import {menuToRoutes} from 'ele-admin';
import NProgress from 'nprogress';

Vue.use(VueRouter);

// 静态路由
const routes = [
  {
    path: '/login',
    component: () => import('@/views/login/login'),
    meta: {title: '登录'}
  },
  {
    path: '/forget',
    component: () => import('@/views/login/forget'),
    meta: {title: '忘记密码'}
  },
  {
    path: '*',
    component: () => import('@/views/exception/404')
  }
];

const router = new VueRouter({
  routes,
  mode: 'hash'
});

// //自定义添加路由
router.$addRoute = (route) => {
  router.matcher = new VueRouter({routes,mode: 'hash'}).matcher;
  router.addRoute(route)
};

// 路由守卫
router.beforeEach((to, from, next) => {
  NProgress.start();
  updateTitle(to);
  // 判断是否登录
  if (setting.takeToken()) {
    // 判断是否已经注册动态路由
    if (!store.state.user.menus) {
      store.dispatch('user/getMenuRouters').then(route => {  // 获取动态路由
        if (route && route.children) {

          route.component = EleLayout;
          // 去除已注册的路由
          // for (let i = route.children.length - 1; i >= 0; i--) {
          //   if (router.resolve(route.children[i].path).resolved.matched.length) {
          //     route.children.splice(i, 1);
          //   }
          // }
          router.$addRoute(route);
        }
        next({...to, replace: true});
      }).catch(() => {
      });
      // // 获取动态路由
      // store.dispatch('user/getMenus').then(({menus, home}) => {
      //   // menuToRoutes方法是把菜单数据转换路由数据格式, 并会过滤掉重复的path, 详细说明到文档中查看
      //   var route = {
      //     name: '/',
      //     path: '/',
      //     component: EleLayout,
      //     redirect: setting.homePath || home,
      //     children: menuToRoutes(menus, (component) => import('@/views' + component))
      //   };
      //   console.log(route);
      //   router.$addRoute(route);
      //   next({...to, replace: true});
      // }).catch(() => {
      //   next();
      // });
    } else {
      next();
    }
  } else if (setting.whiteList.indexOf(to.path) !== -1) {
    next();  // 在无需登录的白名单内
  } else {
    // 未登录跳转登录页面
    next({path: '/login', query: to.path === '/' ? {} : {from: to.path}});
  }
});

router.afterEach(() => {
  setTimeout(() => {
    NProgress.done(true);
  }, 300);
});

export default router;

/**
 * 更新浏览器标题
 * @param route 路由
 */
function updateTitle(route) {
  let names = [];
  if (route && route.meta && route.meta.title) {
    names.unshift(route.meta.title);
  }
  const appName = process.env.VUE_APP_NAME;
  if (appName) {
    names.unshift(appName);
  }
  document.title = names.join(' - ');
}
